//
//  ViewController.m
//  OC注入JS
//
//  Created by YYY on 2018/1/4.
//  Copyright © 2018年 YYY. All rights reserved.
//

#import "ViewController.h"

#import <JavaScriptCore/JavaScriptCore.h>

@interface ViewController () <UIWebViewDelegate>

@property (nonatomic,strong)UIWebView *webView;

@property(nonatomic,strong)NSMutableArray *imagesArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
     [self.view addSubview:self.webView];
    
    //加载浏览网页
    /*
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]];
    [self.webView loadRequest:request];
    */
    
    //加载本地html
    NSString *path = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
    NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
    [self.webView loadRequest:request1];
}

- (UIWebView *)webView
{
    if (_webView == nil)
    {
        _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        _webView.delegate = self;
        _webView.scrollView.scrollsToTop = NO;
        _webView.backgroundColor = [UIColor whiteColor];
    }
    return _webView;
}

- (NSMutableArray *)imagesArray
{
    if (!_imagesArray)
    {
        _imagesArray = [NSMutableArray array];
    }
    return _imagesArray;
}
#pragma mark UIWebView delegate
//进行加载前的预判断，如果返回YES，则会进入后续流程（StartLoad,FinishLoad）。如果返回NO，这不会进入后续流程。
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([request.URL.scheme isEqualToString:@"image-preview"]) {
        NSString *clickImage = request.URL.resourceSpecifier;
        NSInteger selectIndex = 0;
        for (int i=0; i<self.imagesArray.count; i++)
        {
            NSString *imageUrl = self.imagesArray[i];
            if ([imageUrl isEqualToString:clickImage])
            {
                selectIndex = i;
                break;
            }
        }
        //展示图片
        [self showImage:clickImage];
        NSLog(@"索引：%ld  当前图片：%@",selectIndex,clickImage);
        return NO;
    }
    return YES;
}
//加载完成
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    /******获取标题方法1******/
    //获取该UIWebView的javascript上下文
    JSContext *jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //在调用前，设置异常回调
    [jsContext setExceptionHandler:^(JSContext *context, JSValue *exception){
        NSLog(@"%@", exception);
    }];
    //这也是一种获取标题的方法。
    JSValue *value = [jsContext evaluateScript:@"document.title"];
    //更新标题
    self.navigationItem.title = value.toString;
    
    /******获取标题方法2******/
    //获取JS标题
    //self.title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    
    /*
    //加载完成注入JS事件
    [self.webView stringByEvaluatingJavaScriptFromString:@"\
     function imageClickAction(){\
     var images = document.getElementsByTagName('img');\
     var length = images.length;\
     for(var i=0;i<length;i++){\
         var img = images[i];\
         img.onclick = function(){\
             window.location.href = 'image-preview:' + this.src;\
         }\
     }\
     }\
     "];
    //触发方法，给所有图片添加onclick方法
    [self.webView stringByEvaluatingJavaScriptFromString:@"imageClickAction()"];
    //获取JS界面的所有图片
    [self getAllImagesFromJS];
     */
    
    
    //这里是js，主要目的实现对url的获取 body
    static  NSString * const jsGetImages =
    @"function getImages(){\
    var objs = document.querySelectorAll(\"body img\");\
                                         var imgScr = '';\
                                         for(var i=0;i<objs.length;i++){\
                                             imgScr = imgScr + objs[i].src + '+';\
                                         };\
                                         return imgScr;\
                                         };";

    
    [self.webView stringByEvaluatingJavaScriptFromString:jsGetImages];
    //注入js方法
    NSString *urlResurlt = [self.webView stringByEvaluatingJavaScriptFromString:@"getImages()"];
    NSLog(@"urlResurlt == %@",urlResurlt);
    
    //添加图片可点击js
    [self.webView stringByEvaluatingJavaScriptFromString:@"function registerImageClickAction(){\
     var imgs = document.querySelectorAll(\"body img\");\
     var length = imgs.length;\
     for(var i=0;i<length;i++){\
     img = imgs[i];\
     img.onclick=function(){\
     window.location.href='image-preview:'+this.src}\
     }\
     }\
     "];
    
    [self.webView stringByEvaluatingJavaScriptFromString:@"registerImageClickAction();"];
    
    [self.imagesArray addObjectsFromArray:[urlResurlt componentsSeparatedByString:@"+"]];

    //OC中调用js方法
    //[self.webView stringByEvaluatingJavaScriptFromString:@"sendMsg('2018与众不同')"];
    
    //[self.webView stringByEvaluatingJavaScriptFromString:@"clickme()"];
    
}
//获取JS界面的所有图片
- (void)getAllImagesFromJS
{
    NSUInteger length = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('img').length"] integerValue];
    //获取图片对应的src
    for (int i=0; i<length; i++)
    {
        NSString *srcString = [NSString stringWithFormat:@"document.getElementsByTagName('img')[%zi].src",i];
        NSString *imageUrl = [self.webView stringByEvaluatingJavaScriptFromString:srcString];
        [self.imagesArray addObject:imageUrl];
    }
    
    NSLog(@"界面图片地址：%@",self.imagesArray);
}

//展示图片
- (void)showImage:(NSString *)imageUrl
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageUrl]];
    [self.webView loadRequest:request];
}
@end
